package thread.demo02.synchronize;

public class SynchronizedDemo {

	// 共享变量
	private boolean ready = false;
	private int result = 0;
	private int num = 1;

	private class ReadWiterThread extends Thread {
		private boolean flag;

		public ReadWiterThread(boolean flag) {
			this.flag = flag;
		}

		@Override
		public void run() {
			if (flag) {
				write();
			} else {
				read();
			}
		}
	}

	public void write() {
		ready = true;
		num = 2;
	}

	// synchronized
	public void read() {
		if (ready) {
			result = num * 3;
		}
		System.out.println("result=" + result);
	}

	public static void main(String[] args) {
		for (int i = 2; i < 100; i++) {
			SynchronizedDemo demo = new SynchronizedDemo();
			demo.new ReadWiterThread(true).start();
			demo.new ReadWiterThread(false).start();
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}